import { Injectable } from '@nestjs/common';
import { Captcha } from './interface/auth.dto';
import * as svgCaptcha from 'svg-captcha';
import { nanoid } from 'nanoid';

@Injectable()
export class CaptchaService {
  private captcha: Map<String, Captcha> = new Map();

  /**
   * @description: 创建验证码
   * @param {}
   * @return {Captcha}
   */
  genCaptcha(): Captcha {
    let isdiffCaptcha = false;
    let c: svgCaptcha.CaptchaObj;
    let captcha: Captcha;
    while (!isdiffCaptcha) {
      c = svgCaptcha.create();
      let text = c.text.toLowerCase();
      if (!this.captcha.has(text)) {
        isdiffCaptcha = true;
        captcha = Object.assign(c, {
          id: nanoid(6),
          text: '',
        });
        this.captcha.set(text, captcha);
      }
    }
    /// 5分钟后图片超时
    setTimeout(() => {
      this.captcha.delete(c.text);
    }, 1000 * 60 * 5);
    return captcha;
  }

  getCaptchaId(text: string): string {
    text = text.toLowerCase();
    return this.captcha.get(text).id;
  }

  checkCaptcha(captcha: Captcha): boolean {
    return captcha.id === this.getCaptchaId(captcha.text);
  }
}
